'''
此文件处理点击和绿文的流程


'''
import glob
import http
import os
import shutil
import threading
import time
import subprocess
import socket
import random
from urllib.parse import urlencode

import pyautogui
# from datetime import time, datetime
import requests
from obswebsocket import obsws

from pt1.xlsx_t import write_to_excel
xlsx_path_临时='/Users/zltest/Desktop/pt1_0325.xlsx'
测试分辨率 = '480'
连接方式 = 'wireless'
存放路径 = '/Users/zltest/Desktop/video.mp4'
new_vd_path = None




def check_scrcpy_mac(max_attempts=3, current_attempt=1):
    """
    检测 macOS 下 scrcpy 是否连接成功，若失败则自动启动（带递归限制）
    :param max_attempts: 最大尝试次数
    :param current_attempt: 当前尝试次数（内部使用）
    :return: True 表示连接成功，False 表示失败
    """
    # 检查是否有 scrcpy 进程（macOS 使用 pgrep）
    try:
        result = subprocess.run(["pgrep", "-f", "scrcpy"], capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ scrcpy 已连接")
            return True
    except subprocess.CalledProcessError:
        pass  # 忽略进程未找到的错误

    # 检查 adb 设备是否已连接
    adb_devices = subprocess.run(["adb", "devices"], capture_output=True, text=True)
    if "device" not in adb_devices.stdout:
        print("❌ 未检测到已连接的安卓设备")
        if current_attempt <= max_attempts:
            print(f"尝试启动 ADB 服务 (第 {current_attempt}/{max_attempts} 次)...")
            subprocess.run(["adb", "kill-server"])
            subprocess.run(["adb", "start-server"])
            time.sleep(2)  # 等待 ADB 重启
            return check_scrcpy_mac(max_attempts, current_attempt + 1)
        else:
            print("⚠️ 已达到最大尝试次数，请检查设备连接")
            return False

    # 若设备已连接但 scrcpy 未运行
    if current_attempt <= max_attempts:
        print(f"🚀 启动 scrcpy (第 {current_attempt}/{max_attempts} 次)...")
        # 启动 scrcpy 并设置高帧率
        subprocess.Popen(["scrcpy", "--max-fps=60", "--video-bit-rate=8M"])
        time.sleep(5)  # 等待 scrcpy 初始化
        return check_scrcpy_mac(max_attempts, current_attempt + 1)
    else:
        print("⚠️ 连接失败，请手动检查")
        return False


def check_connected_devices():
    """
    检查是否有设备连接到 ADB。
    :return: 如果有设备连接，返回设备 ID 列表；如果没有设备连接，抛出异常。
    """
    try:

        result = subprocess.run(['adb', 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        # 捕获标准输出
        output = result.stdout.strip()

        # 解析输出，获取设备列表
        lines = output.splitlines()
        if len(lines) <= 1:
            raise Exception("没有设备连接到 ADB")

        # 提取设备 ID（跳过标题行）
        device_list = []
        for line in lines[1:]:
            if line.strip() and "device" in line:
                device_id = line.split()[0]
                device_list.append(device_id)

        if not device_list:
            raise Exception("没有设备连接到 ADB")

        return device_list
    except Exception as e:
        raise Exception(f"检查设备时出错: {e}")


def resolve_dns(hostname):
    """
    手动进行 DNS 解析并缓存结果。
    """
    return socket.gethostbyname(hostname)


        # 其他常用操作：
        # ws.call(requests.StopRecord())  # 停止录制
        # ws.call(requests.StartStream())  # 开始推流
        # ws.call(requests.SetCurrentScene("场景名称"))  # 切换场景

    # finally:
    #     ws.disconnect()

def click_green():
    """
    点击绿色按钮逻辑，确保至少有一个设备连接。
    """
    try:
        # 检查是否有设备连接
        devices = check_connected_devices()
        print("已连接设备:", devices)

    except Exception as e:
        print(f"错误: {e}")
        return

    # 检查scrcpy是否连接在线
    check_scrcpy_mac()

    # # 定义基础 URL 和查询参数
    hostname = "192.168.1.87"  # ，替换为实际域名
    path = "/cmd"

    # 手动解析 DNS 并缓存 IP 地址
    ip_address = resolve_dns(hostname)
    print(f"DNS 解析完成: {hostname} -> {ip_address}")

    # 使用 HTTP 长连接
    conn = http.client.HTTPConnection(ip_address, timeout=5)

    # 下面是obs的web配置
    from obswebsocket import obsws, requests
    # 连接配置
    host = "localhost"
    port = 4455
    # 建立连接
    ws = obsws(host, port)
    ws.connect()
    # 定义查询参数
    params_摄像头 = {"t": 1}
    点击屏幕 = {"t": 2}
    success_click = []

    # 将查询参数转换为合法的查询字符串
    query_string_摄像头 = urlencode(params_摄像头)
    query_string_点击屏幕 = urlencode(点击屏幕)

    try:
        # 发送初始请求（开始摄像）
        conn.request("GET", f"{path}?{query_string_摄像头}")
        ws.call(requests.StartRecord())
        # 开始计时
        start_time = time.perf_counter()
        response = conn.getresponse()
        response.read()  # 消费响应体

        for i in range(10):
            time.sleep(1.5)  # 每次循环等待 1.5 秒
            try:
                # 发送 GET 请求
                # 记录请求前的时间
                request_start_time = time.perf_counter() - start_time
                conn.request("GET", f"{path}?{query_string_点击屏幕}")
                request_start_time_1 = time.perf_counter() - start_time
                response = conn.getresponse()
                response.read()
                really_time = (request_start_time+request_start_time_1)/2
                # print(f"前浪时间: {request_start_time:.6f} 秒")
                # print(f"后浪时间: {request_start_time_1:.6f} 秒")
                print(f"第{i+1}次的时间: {really_time:.6f}秒\n\n")
                click_时间 = round(really_time, 3)
                success_click.append(click_时间)


                if response.status != 200:
                    print(f"第{i + 1}次点击屏幕出错，状态码: {response.status}")
                    break

                # print(f"第{i + 1}次点击屏幕完成，响应数据: {data.decode()}")

            except Exception as e:
                print(f"第{i + 1}次点击屏幕出错，错误信息: {e}")
                import traceback
                traceback.print_exc()  # 打印完整的堆栈信息
                break

        conn.request("GET", f"{path}?{query_string_摄像头}")
        response = conn.getresponse()
        # 必须读取完整的响应数据
        data = response.read()
        if response.status != 200:
            print('无法结束摄像')
            return
        print(f"结束摄像的响应状态码: {response.status}")



    finally:
        # 总耗时
        total_elapsed_time = time.perf_counter() - start_time
        print(f"总耗时: {total_elapsed_time:.3f} 秒")
        print(success_click)
        # 关闭连接（循环结束后统一关闭）
        conn.close()
        # 让obs录完视频
        time.sleep(1)
        ws.call(requests.StopRecord())
        print("已结束对车机的视频录制")

    # # 拼接视频名字
    # hu_name = 连接方式 + '_' + 测试分辨率  + '_vd'  + '.mp4'


    # 下面步骤是把new_vd_path传递进生成慢放绿文视频的函数模块
    path = rename_obs_recording(connection_type=连接方式, resolution=测试分辨率, )
    print(path)


    write_to_excel(success_click, file_path=xlsx_path_临时, resolution=测试分辨率)


def rename_obs_recording(connection_type, resolution, output_dir="/Users/zltest/Desktop"):
    """
    安全重命名OBS视频文件
    :param connection_type: 连接方式（如 'wireless'）
    :param resolution: 分辨率（如 '480'）
    :param output_dir: 视频保存目录
    :return: 新文件完整路径
    """
    # 1. 获取OBS生成的文件
    obs_pattern = os.path.join(output_dir, "[0-9][0-9]-[0-9][0-9] [0-9][0-9]-[0-9][0-9]-[0-9][0-9].mp4")
    obs_files = glob.glob(obs_pattern)

    if not obs_files:
        raise FileNotFoundError("未找到OBS生成的视频文件")

    # 2. 获取最新文件
    latest_file = max(obs_files, key=os.path.getmtime)

    # 3. 生成唯一新文件名
    base_name = f"{connection_type}_{resolution}_vd"
    new_name = f"{base_name}.mp4"
    new_vd_path = os.path.join(output_dir, new_name)

    # 处理文件名冲突
    counter = 1
    while os.path.exists(new_vd_path):
        new_name = f"{base_name}_{counter}.mp4"
        new_vd_path = os.path.join(output_dir, new_name)
        counter += 1

    # 4. 复制并删除原文件
    try:
        shutil.copy2(latest_file, new_vd_path)
        os.remove(latest_file)
        print(f"文件已重命名: {os.path.basename(latest_file)} → {new_name}")
    except OSError as e:
        print(f"操作失败: {e}")
        raise

    return new_vd_path

if __name__ == '__main__':
    click_green()


